package com.demo.main.servlet;

import com.demo.main.entity.BookCategory;
import com.demo.main.service.BookCategoryService;
import com.demo.main.utils.JSONUtil;
import com.demo.main.utils.ServletUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.demo.main.utils.ServletUtil.PERMISSION_PATH_ADMIN;

@WebServlet({PERMISSION_PATH_ADMIN + "/book_category_condition",
        PERMISSION_PATH_ADMIN + "/book_category_edit",
        PERMISSION_PATH_ADMIN + "/book_category_delete",
        PERMISSION_PATH_ADMIN + "/book_category_add"})
public class BookCategoryServlet extends HttpServlet {

    private final BookCategoryService bookCategoryService = new BookCategoryService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletUtil servletUtil = new ServletUtil(request, response);
        switch (servletUtil.getServletPath()) {
            case PERMISSION_PATH_ADMIN + "/book_category_condition":
                request.setAttribute("list", bookCategoryService.findByCondition(servletUtil.convertRequestParameter(BookCategory.class)));
                servletUtil.forward(PERMISSION_PATH_ADMIN + "/view/book_category_management");
                break;
            case PERMISSION_PATH_ADMIN + "/book_category_edit":
                bookCategoryService.updateById(servletUtil.convertRequestParameter(BookCategory.class));
                servletUtil.forward(PERMISSION_PATH_ADMIN + "/view/book_category_management");
                break;
            case PERMISSION_PATH_ADMIN + "/book_category_delete":
                // ajax
                bookCategoryService.deleteById(servletUtil.getParameterAs("id", Integer.class));
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("message", "删除成功");
                resultMap.put("isSuccess", true);
                response.getWriter().println(JSONUtil.mapToJson(resultMap));
                break;
            case PERMISSION_PATH_ADMIN + "/book_category_add":
                bookCategoryService.addOne(servletUtil.convertRequestParameter(BookCategory.class));
                servletUtil.forward(PERMISSION_PATH_ADMIN + "/view/book_category_management");
                break;
        }
    }
}
